<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Libs\WeChatPublic;
use DB;
use Cache;
use Log;

class WeChatController extends Controller
{
    //微信绑定，展示二维码页面
    public function weChatBind()
    {
        $wx = new WeChatPublic();
        $id = auth('admin')->user()->id;
        $info = $wx->getQrCodeInfo($id, 120);
        $url = $info['url'];
        // echo $info['ticket']."<br>";
        // file_put_contents("ticket.txt", $info['ticket']."\r\n",FILE_APPEND);
        return view('admin.weChat.weChatBind', compact('url'));
    }

    //微信服务器会将请求 post 发送到这里
    public function interfaceCheck(Request $request)
    {
        $wx = new WeChatPublic();
        // $wx->interfaceCheck();return;//接口配置信息验证
        $obj = $wx->getSimpleXMLElement();
        $data = print_r($obj, true);
        file_put_contents("weChat00.txt", $data);
        Log::info($data);

        if ($obj) {
            # 确实为微信服务器发送的请求
            $open_id = $obj->FromUserName;
            $dev_id = $obj->ToUserName;
            $msg = "服务器未处理";

            switch ($obj->MsgType) {
                case 'event':
                    # 事件触发
                    if ($obj->Event == "SCAN" || ($obj->Event == "subscribe" && (string) ($obj->EventKey))) {
                        # 扫描带参数二维码事件 (用户已关注/用户未关注)
                        $eventKey = ltrim($obj->EventKey, "qrscene_");
                        $eventKeyArr = explode("***", $eventKey);//字符串转数组
                        $appName = $eventKeyArr[0];
                        $sceneStr = $eventKeyArr[1];

                        // config(['database.connections.mysql.database' => config('constant.db_database_' . $appName)]);//在运行时修改配置
                        // config(['database.connections.mysql.username' => config('constant.db_username_' . $appName)]);//在运行时修改配置
                        // config(['database.connections.mysql.password' => config('constant.db_password_' . $appName)]);//在运行时修改配置

                        if ($sceneStr == 'login') {
                            # 登录
                            $user_info = DB::connection("mysql_{$appName}")->table('manager')->where('open_id', $open_id)->first();
                            if ($user_info) {
                                # code...
                                switch ($user_info->status) {
                                        // 账号状态，1-未启用，2-启用，3-禁用
                                    case '2':
                                        # 启用
                                        // 注意：如果该键已经存在，则直接覆盖原来的值，有效期必须设置，单位是分钟
                                        // 语法：Cache::put('key', 'value', $minutes);
                                        $cache_data['login_id'] = $user_info->id;
                                        config(['cache.stores.file.path' => config('constant.cache_file_path')]);//在运行时修改配置
                                        Cache::put("T_" . $obj->Ticket,  $cache_data, 1);

        Log::info(Cache::get("T_" . $obj->Ticket));
                                        $now=date("Y-m-d H:i:s");
                                        $msg = "[$now]\n微信扫码登录成功";
                                        break;
                                    case '3':
                                        # 禁用
                                        $msg = "您的账号已被禁用";
                                        break;
                                    case '1':
                                        # 未启用
                                        $msg = "您的账号尚未启用";
                                        break;
                                    default:
                                        # code...
                                        break;
                                }
                            } else {
                                $msg = "您的账号还没有绑定微信";
                            }
                        } else {
                            # 绑定
                            $user_id = $sceneStr;
                            $user_info = DB::connection("mysql_{$appName}")->table('manager')->where('open_id', $open_id)->first();
                            if ($user_info) {
                                # code...
                                $msg = "您的微信已经绑定了账号【{$user_info->username}】，\n不能再次绑定";
                            } else {
                                # code...
                                DB::connection("mysql_{$appName}")->table('manager')->where('id', $user_id)->update(["open_id" => $open_id]);
                                $msg = "绑定成功";
                            }

                        }
                    } else if ($obj->Event == "subscribe") {
                        # 关注事件
                        $msg = "欢迎来到【汇邦检测】服务号";
                    }

                    break;
                case 'text':
                    # 文本消息
                    $msg = "鹦鹉学舌：{$obj->Content}";
                    break;
                case 'voice':
                    # 语音消息
                    $msg = "鹦鹉学舌：{$obj->Recognition}";
                    break;
                default:
                    # code...
                    break;
            }


            $xml = <<<eof
            <xml>
                <ToUserName><![CDATA[$open_id]]></ToUserName>
                <FromUserName><![CDATA[$dev_id]]></FromUserName>
                <CreateTime>12345678</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[$msg]]></Content>
            </xml>
eof;
            return $xml;
        }
    }
}
